//
//  MXWebPopupView.swift
//  d11
//
//  Created by peale_pro on 2019/7/17.
//  Copyright © 2019年 Tech_001. All rights reserved.
//

import UIKit
import JavaScriptCore
import Eagleeyes.DevicePrint
class MXWebPopupView: UIView, UIWebViewDelegate,CAAnimationDelegate {
    
    var imgName :String?
    var typeName:String?
    let customScheme = "customredirect"
    let customHttpsScheme = "customredirects"
    
    var webView: UIWebView?
    var signLoging:Bool?
    var url: String?
    var isLoadjsCode = false
    var jsContext: JSContext!
    var isKefu = false
    var needSetUserInfo = false
    var isEagleeyes :Bool = false
    var isHorizontalScreen :Bool = false
    var _loadView: UIView?
    var popScreenWidth : CGFloat = kScreenWidth
    var ipadAddHeight :CGFloat = 100
    var whiteView :UIView?
    var isClose = false
    convenience init(imgName:String,typeName:String,toPath:String,isHorizontalScreen:Bool) {
        self.init(frame: UIScreen.main.bounds)
        let window: UIWindow  = ((UIApplication.shared.delegate?.window)!)!
        self.backgroundColor = UIColor.clear
        window.addSubview(self)
        self.url  = "https://" + UserDefaults.standard.string(forKey: DefaultKey.USER_DOMAIN)! + toPath
        self.imgName  = imgName
        self.typeName = typeName
        self.isHorizontalScreen = isHorizontalScreen
        self.popScreenWidth = kScreenWidth
        if kIsIpad == true{
            if kScreenWidth < 415+100{
                self.popScreenWidth = kScreenWidth
                self.ipadAddHeight = kScreenWidth-415
            }else{
                self.popScreenWidth = 415+100
            }
            
        }else{
            self.ipadAddHeight = 0
        }
        //感知设备方向 - 开启监听设备方向
        UIDevice.current.beginGeneratingDeviceOrientationNotifications()
        //添加通知，监听设备方向改变
        NotificationCenter.default.addObserver(self, selector: #selector(MXWebPopupView.receivedRotation), name: UIDevice.orientationDidChangeNotification, object: nil)
        self.initUI()
      //  self.whiteView?.layer.add(self.createAnimation(keyPath: "transform.scale", toValue: 1,fromValue: 0), forKey: nil)
        
    }
    
    @objc func receivedRotation(){
        self.closePageView()
    }
    @objc func closePageView() -> Void {
       // self.isClose = true
       // self.whiteView?.layer.add(self.createAnimation(keyPath: "transform.scale", toValue: 0,fromValue: 1), forKey: nil)
        self.removeFromSuperview()
    }
    
    //创建基础Animation
    func createAnimation (keyPath: String, toValue: CGFloat,fromValue:CGFloat) -> CABasicAnimation {
        //创建动画对象
        let scaleAni = CABasicAnimation()
        //设置动画属性
        scaleAni.keyPath = keyPath
        
        //设置动画的起始位置。也就是动画从哪里到哪里。不指定起点，默认就从positoin开始
        scaleAni.toValue = toValue
        scaleAni.fromValue = fromValue
        //动画持续时间
        scaleAni.duration = 0.5;
        scaleAni.delegate = self
        //动画重复次数
        scaleAni.repeatCount = 1
        
        return scaleAni;
    }
    func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
        if isClose == true{
            self.removeFromSuperview()
            isClose = false
        }
    }
    func initUI(){
        let bgView :UIView  = UIView.init()
        bgView.backgroundColor = RGBAlpa(0,0,0,0.4)
        bgView.tag = 3001
        bgView.isUserInteractionEnabled = true
        bgView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(closePageView)))
        let window: UIWindow  = ((UIApplication.shared.delegate?.window)!)!
        ////        let effecView = UIHelper.showBlurEffect(isClick:true)
        ////       window.addSubview(effecView)
        self.addSubview(bgView)
        bgView.snp.makeConstraints { (make) in
            make.width.equalToSuperview()
            make.height.equalToSuperview()
            make.top.equalToSuperview()
            make.bottom.equalToSuperview()
        }
        
        self.whiteView = UIView.init()
        self.whiteView?.backgroundColor = HexRGBAlpha(0xf6f8fa, 1)
        self.whiteView?.layer.cornerRadius = 5;
        self.whiteView?.layer.masksToBounds = true
        self.addSubview(self.whiteView!)
        whiteView?.snp.makeConstraints { (make) in
            if kIsIpad == true{
                make.width.equalTo(self.popScreenWidth-20)
            }else{
                if self.isHorizontalScreen == true{
                    make.width.equalTo(self.snp.height).offset(-20)
                }else{
                    make.width.equalToSuperview().offset(-20)
                }
            }
            if kScreenWidth <= 320 && self.isHorizontalScreen == true {
                make.height.equalTo(300)
            }else{
                make.height.equalTo(350+self.ipadAddHeight)
            }
            
            make.centerY.equalToSuperview()
            make.centerX.equalToSuperview()
        }
        
        let iconImageView = UIImageView.init()
        iconImageView.image = UIImage.init(named: self.imgName ?? "")
        self.whiteView?.addSubview(iconImageView)
        iconImageView.snp.makeConstraints{(make) in
            make.width.equalTo(25)
            make.height.equalTo(25)
            make.top.equalToSuperview().offset(10)
            make.left.equalToSuperview().offset(20)
        }
       
        
        
        let closeLabel = UILabel.init()
        closeLabel.textColor = HexRGBAlpha(0x747474, 1)
        closeLabel.font = UIFont.systemFont(ofSize: 20)
        closeLabel.text =  "X"
        closeLabel.textAlignment = .right
        closeLabel.isUserInteractionEnabled = true
        closeLabel.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(closePageView)))
        self.whiteView?.addSubview(closeLabel)
        closeLabel.snp.makeConstraints{(make) in
            make.right.equalToSuperview().offset(-10)
            make.height.equalTo(25)
            make.width.equalTo(40)
            make.top.equalToSuperview().offset(10)
        }
        
        let nameLabel = UILabel.init()
        nameLabel.textColor = HexRGBAlpha(0x747474, 1)
        nameLabel.font = UIFont.systemFont(ofSize: 15)
        nameLabel.text =  self.typeName
        nameLabel.textAlignment = .left
        self.whiteView?.addSubview(nameLabel)
        nameLabel.snp.makeConstraints{(make) in
            make.left.equalTo(iconImageView.snp.right).offset(15)
            make.right.equalTo(closeLabel.snp.left).offset(15)
            make.height.equalTo(25)
            make.top.equalToSuperview().offset(10)
        }
        
         self.webView = UIWebView()
        webView?.scalesPageToFit = true
        self.whiteView?.addSubview(webView!)
        webView?.snp.makeConstraints{(make) in
            make.top.equalTo(nameLabel.snp.bottom).offset(10)
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.bottom.equalToSuperview().offset(-10)
        }
        if self.url?.contains("activity=yeiQC5hLS2tD5jq6flMl3dvympPZ7K9r") ?? false {
            self.needSetUserInfo = true
        }
        if let urlString = self.url {
            if let urlObj = URL(string: urlString){
                let request = URLRequest(url: urlObj)
                webView!.delegate = self
                webView!.loadRequest(request)
            }
        }
    }
    
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool {
        if (self.isEagleeyes == true){
            if (request.url?.scheme != "e2"){
                return true
            }
            if (request.url?.fragment == nil){
                return true
            }
            let blackBox : String =  DevicePrint.getBlackBox() ?? ""
            webView.stringByEvaluatingJavaScript(from: "document.getElementById('\(request.url?.fragment ?? "" )').value = '\(blackBox)'")
            return false
        }else{
            if let app = WebViewApp.getInstance(request.url!) {
                WebViewApp.route(app)
                return false
            }
            
            if request.url?.scheme == self.customScheme {
                let newUrl = URL(string: request.url!.absoluteString.replacingOccurrences(of: self.customScheme, with: "http"))
                UIApplication.shared.openURL(newUrl!)
                return false
            }else if request.url?.scheme == self.customHttpsScheme {
                let newUrl = URL(string: request.url!.absoluteString.replacingOccurrences(of: self.customHttpsScheme, with: "https"))
                UIApplication.shared.openURL(newUrl!)
                return false
            }
            
            
            print(navigationType)
            return true
        }
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        if self._loadView != nil {
            self._loadView?.removeFromSuperview()
        }
        self._loadView = UIHelper.initLoadView2(withMessage: nil, offsetY: 0)
       // self._loadView?.isUserInteractionEnabled = true
       // self._loadView?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(closePageView)))
        self.addSubview(self._loadView!)
        
        for cookie in HTTPCookieStorage.shared.cookies(for: URL(string: url!)!)! {
            print("Cookie: \(cookie.name), value: \(cookie.value)")
        }
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        print("WebView Target: \(webView.request?.url?.absoluteString)")
        if (self.isEagleeyes == true){//鷹眼
            let blackBox : String =  DevicePrint.getBlackBox() ?? ""
            webView.stringByEvaluatingJavaScript(from: "document.getElementById('bbox').value = '\(blackBox)'")
            webView.stringByEvaluatingJavaScript(from: "var DevicePrint = { injectInto: function(id) { var iframe = document.createElement('IFRAME');  iframe.setAttribute('src', 'e2://blackbox/fill#' + id);  document.documentElement.appendChild(iframe);  iframe.parentNode.removeChild(iframe); iframe = null; } }")
        }
        
        webView.stringByEvaluatingJavaScript(from: "window.open = function (open) { return function  (url, name, features) { var newurl = url.replace('https://','\(self.customHttpsScheme)://'); newurl = newurl.replace('http://','\(self.customScheme)://'); window.location.href = newurl; return window; }; } (window.open);")
        //mt 20171229
        
        
        let defaults = UserDefaults.standard
        
        var mtusername = ""
        if UserHelper.getLoginStatus() {
            mtusername = (defaults.value(forKey: DefaultKey.USER_LOGIN_NAME) as? String)!
        }
        
        if self.url?.contains("addcs=a22e83d19bf3d90f")  == true {
            
        }else{
            webView.stringByEvaluatingJavaScript(from:"javascript: var masigle = true; var setIntVal=setInterval(function(){var msnElements = document.getElementsByName('msn'); if(msnElements.length>=1){clearInterval(setIntVal); if(msnElements&&masigle){for(var i=0;i<msnElements.length;i++){msnElements[i].value='\(mtusername)'} masigle = false;}} var funcHistory = document.getElementById('history');funcHistory.style.overflow='visible';var funcQueue = document.getElementById('queue'); funcQueue.style.display='block';var funcDiv=document.getElementById('funcDiv');funcDiv.style.position='fixed';funcHistory.style.bottom='0px';funcHistory.style.top='0px';funcQueue.style.zIndex=0; } ,500);")
        }
        
        self.jsContext = webView.value(forKeyPath: "documentView.webView.mainFrame.javaScriptContext") as! JSContext
        if isLoadjsCode {
            print("传递的参数:\(UserDefaults.standard.string(forKey: DefaultKey.USER_LOGIN_NAME)! as NSString)   \(UserDefaults.standard.string(forKey: DefaultKey.USER_DOMAIN)! as NSString)")
            self.jsContext.evaluateScript("getAccount('\( UserDefaults.standard.string(forKey: DefaultKey.USER_LOGIN_NAME)! as NSString)' ,'\( UserDefaults.standard.string(forKey: DefaultKey.USER_DOMAIN)! as NSString)')")
        }
        if needSetUserInfo{
            print("传递的参数:\(UserDefaults.standard.string(forKey: DefaultKey.USER_LOGIN_NAME)! as NSString)   \(UserDefaults.standard.string(forKey: DefaultKey.USER_DOMAIN)! as NSString)")
            self.jsContext.evaluateScript("setActivityParam('\( UserDefaults.standard.string(forKey: DefaultKey.USER_LOGIN_NAME)! as NSString)' ,'\( UserDefaults.standard.string(forKey: DefaultKey.USER_DOMAIN)! as NSString)')")
        }
        let model = SwiftJavaScriptModel()
        self.jsContext.setObject(model, forKeyedSubscript: "ios" as NSCopying & NSObjectProtocol)
        /*js调用swift方法结束*/
        self._loadView?.removeFromSuperview()
        
    }
    
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        if self._loadView != nil {
            self._loadView?.removeFromSuperview()
        }
    }
}
